package org.jmeter.tcp.helmet;

import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.jmeter.tcp.helmet.gps.Gps;
import org.jmeter.tcp.helmet.gps.PushGpsUtils;

import java.io.FileInputStream;
import java.util.List;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/11/13 15:23
 * @since
 */
public class HelmetGpsPushSampler extends AbstractSampler {
    private static final Logger log = LoggingManager.getLoggerForClass();
    private final static String ADDRESS = "address";
    private final static String DEV_ID = "devId";
    private final static String FILE_PATH = "filePath";

    public String getAddress() {
        return getPropertyAsString(ADDRESS);
    }

    public void setAddress(String address) {
        setProperty(ADDRESS, address);
    }

    public String getDevId() {
        return getPropertyAsString(DEV_ID);
    }

    public void setDevId(String devId) {
        setProperty(DEV_ID, devId);
    }

    public String getFilePath() {
        return getPropertyAsString(FILE_PATH);
    }

    public void setFilePath(String filePath) {
        setProperty(FILE_PATH, filePath);
    }

    @Override
    public SampleResult sample(Entry entry) {
        SampleResult result = new SampleResult();

        result.setSampleLabel(getName());
        result.setSuccessful(false);
        result.setResponseCode("500");

        result.sampleStart(); // 开始
        try {
            String samplerData = null;

            String devId = getDevId();
            // 解析gps数据
            List<Gps> gpsList = PushGpsUtils.parseGps(new FileInputStream(getFilePath()));

            // 样本数据
            samplerData = "devId:" + devId;
            samplerData += "\n推送gps总数：" + gpsList.size();
            result.setSamplerData(samplerData);

            Boolean success = PushGpsUtils.pushHttpGpsDelayWithTask(gpsList, devId, 10, getAddress());
            if(success){
                result.setSuccessful(true);
                result.setResponseCode("200");
                result.setResponseData("gps异步推送，耐心等待，推送进度请看日志信息", "utf-8");
            }else{
                result.setResponseData("任务重复提交", "utf-8");
            }

        }catch (Exception e){
            log.error("未知异常", e);
            result.setResponseData(e.getMessage(), "utf-8");
        }finally {
            result.sampleEnd();
        }
        log.info("开始执行sample方法");

        return result;
    }





}
